package com.py.credit.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PushbackInputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.PromiseBookLog;
import com.py.credit.entity.PromiseBookReport;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.PromiseBookReportEnum;
import com.py.credit.service.PromiseBookReportService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.FileUtils;
import com.py.credit.utils.MapCache;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;
import com.py.framework.core.exception.ServiceException;
import com.py.framework.core.helper.HttpServletHelper;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.log.level.ErrorLog;

@RestController
@RequestMapping(value = "/promiseBook")
public class PromiseBookReportController {

	private final static String FRONT_TABLE_ID = "promiseBook";

	private static FormulaEvaluator evaluator;

	@Autowired
	private PromiseBookReportService promiseBookReportService;

	@Autowired
	private RemoteBaseService remoteBaseService;

	@Value("${absolutepath}")
	private String absolutepath;

	/**
	 * 查询本单位上报的所有未删除的承诺书 高级检索
	 * 
	 * @param type
	 *            承诺书类型:主动承诺和行业自律型承诺（ZD）、审批替代型承诺（SP）、容缺受理型承诺（RQ）、失信修复型承诺（SX）',
	 * @param ztType
	 *            主体类型：
	 * @param bookStatus
	 *            承诺书上报状态：初始状态（0），待审核（1），审核通过（2），驳回（3）,
	 * @param relationStatus
	 *            承诺书关联状态：未关联（0），已关联（1）
	 * @param havBook
	 *            是否有承诺书：没有（0），有（1）
	 * @param condition
	 * @param page
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getPromiseBooks.json")
	public RestServiceResult<List<Map<String, Object>>> getPromiseBooks(
			@RequestParam(value = "type", required = false, defaultValue = "") String type,
			@RequestParam(value = "ztType", required = false, defaultValue = "") String ztType,
			@RequestParam(value = "bookStatus", required = false, defaultValue = "") String bookStatus,
			@RequestParam(value = "havBook", required = false, defaultValue = "") String havBook,
			@RequestParam(value = "sbtype", required = false, defaultValue = "") String sbtype,
			@RequestParam(value = "condition", defaultValue = "", required = false) String condition, Page page,
			HttpServletRequest request) {

		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null != userInfo) {

			} else {
				ExceptionLogger.error("PromiseBookReportController#getPromiseBooks", "未获取到当前用户信息！");
				throw new ServiceException("未获取到当前用户信息！");
			}
		} else {
			ExceptionLogger.error("PromiseBookReportController#getPromiseBooks", "未获取到当前用户信息！");
			throw new ServiceException("未获取到当前用户信息！");
		}

		String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_ID);

		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? PromiseBookReportEnum.getDefaultShowColumnEN()
				: Arrays.asList(configColumns);
		String[] additionalColumns = { "id", "path", "tybm", "deptId", "isDel", "reportUserId", "areaId", "parentId",
				"batchId", "areaName" };

		Long areaId = userInfo.getAreaId();
		Long userId = userInfo.getId();
		Long deptId = userInfo.getOfficeId();
		String rolename = userInfo.getRoleName();
		int userType = userInfo.getUserType();

		String sql = "";
		

		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			if(rolename.equals("系统管理员")) {
				list = promiseBookReportService.getPromiseBooksByConditionForPage(type, ztType,
						bookStatus, havBook, sql, showColumns, additionalColumns, condition, page,null,null,sbtype);
			}else if(rolename.equals("部门管理员")) {
				list = promiseBookReportService.getPromiseBooksByConditionForPage(type, ztType,
						bookStatus, havBook, sql, showColumns, additionalColumns, condition, page,deptId,null,sbtype);
			}else {
				list = promiseBookReportService.getPromiseBooksByConditionForPage(type, ztType,
						bookStatus, havBook, sql, showColumns, additionalColumns, condition, page,deptId,userId,sbtype);
			}
		

			result.setData(list);
			result.setCount(page.getTotalCount());
			result.setCode(RestServiceResult.CODE_SUCCESS);

		} catch (Exception e) {
			ExceptionLogger.error("PromiseBookReportController#getPromiseBooks", "系统异常，请联系管理员！");

			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("系统异常，请联系管理员！");
		}

		return result;
	}

	/**
	 * 修改承诺书上报
	 * 
	 * @param file
	 *            承诺书图片
	 * @param name
	 *            承诺书名称
	 * @param type
	 *            承诺书类型：主动承诺和行业自律型承诺（ZD）、审批替代型承诺（SP）、容缺受理型承诺（RQ）、失信修复型承诺（SX）
	 * @param ztName
	 *            主体名称
	 * @param ztType
	 *            主体类型 'P','C','F'
	 * @param tyshxydm
	 *            统一社会信用代码
	 * @param request
	 * @return 插入成功/失败
	 */
	@RequestMapping(value = "/savePromiseBook.json")
	public RestServiceResult<Object> savePromiseBook(@RequestParam(required = false, value = "file") MultipartFile file,
			@RequestParam(value = "type", required = true, defaultValue = "") String type,
			@RequestParam(value = "name", required = false, defaultValue = "") String name,
			@RequestParam(value = "ztName", required = true, defaultValue = "") String ztName,
			@RequestParam(value = "tyshxydm", required = true, defaultValue = "") String tyshxydm,
			@RequestParam(value = "id", required = true, defaultValue = "") Long id, HttpServletRequest request) {

		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo) {
				ExceptionLogger.error("PromiseBookReportController#savePromiseBook", "未获取到当前用户信息！");
				return new RestServiceResult<Object>(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
			}
		} else {
			ExceptionLogger.error("PromiseBookReportController#savePromiseBook", "未获取到当前用户信息！");
			return new RestServiceResult<Object>(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
		}

		RestServiceResult<Object> result = new RestServiceResult<Object>();

		if (file != null) {
			String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),
					file.getOriginalFilename().length());
			if (!".jpg".equalsIgnoreCase(fileType) && !".png".equalsIgnoreCase(fileType)
					&& !".JPG".equalsIgnoreCase(fileType) && !".PNG".equalsIgnoreCase(fileType)) {

				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("承诺书图片暂时不支持jpg/png以外的格式。");
				return result;
			}
		}

		if (name.length() > 50) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("承诺书名称不允许大于50！");

			return result;
		}

		if (!StringUtils.isEmpty(tyshxydm)) {
			if (tyshxydm.length() != 18) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("主体代码必须为18位！");

				return result;
			}
		}

		if (!StringUtils.isEmpty(type)) {
			if (tyshxydm.length() > 100) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("承诺书类型过长！");

				return result;
			}
		} else {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("承诺书类型不能为空！");

			return result;
		}

		if (!StringUtils.isEmpty(ztName)) {
			if (ztName.length() > 50) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("主体名称长度不能大于50！");

				return result;
			}
		} else {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("主体名称不能为空！");

			return result;
		}

		try {
			int successCount = promiseBookReportService.savePromiseBook(absolutepath, type, ztName, tyshxydm, file,
					userInfo.getOfficeId(), userInfo.getOfficeName(), id);

			if (successCount <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("保存失败！");

			} else {
				result.setCode(RestServiceResult.CODE_SUCCESS);
				result.setMsg("保存成功！");
			}
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("系统异常，请联系管理员！！！");
		}

		return result;
	}

	/**
	 * 批量删除上传承诺书的记录（改变is_del状态为‘Y’）
	 * 
	 * @param ids
	 *            每条记录的id（1,2,3。。。）
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/delPromiseBook.json")
	public RestServiceResult<Object> delPromiseBook(@RequestParam(value = "ids", required = true) String ids,
			HttpServletRequest request) {
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null != userInfo) {

			} else {
				ExceptionLogger.error("PromiseBookReportController#delPromiseBook", "未获取到当前用户信息！");
				return new RestServiceResult<Object>(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
			}
		} else {
			ExceptionLogger.error("PromiseBookReportController#delPromiseBook", "未获取到当前用户信息！");
			return new RestServiceResult<Object>(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
		}

		RestServiceResult<Object> result = new RestServiceResult<Object>();

		List<Long> idList = new ArrayList<Long>();
		String[] idArr = ids.split(",");
		for (String id : idArr) {
			idList.add(Long.parseLong(id));
		}

		Iterator<Long> it = idList.iterator();
		try {
			while (it.hasNext()) {

				Long id = it.next();

				Map<String, String> isOkMap = promiseBookReportService.selectCount(id);

				String bookStatus = isOkMap.get("bookStatus");
				if(!userInfo.getRoleName().equals("系统管理员")) {
					if ("1".equals(bookStatus) || "2".equals(bookStatus)) {
						it.remove();
					}
				}
				
			}

			int successCount = 0;
			if (idList.size() > 0) {
				successCount = promiseBookReportService.delPromiseBooks(idList);
			}

			if (successCount <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("待审核和审批通过的数据无法删除！");

			} else {
				result.setCode(RestServiceResult.CODE_SUCCESS);
				result.setMsg("删除成功！");
			}
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("系统异常，请联系管理员！！！");
		}
		return result;
	}

	/**
	 * 
	 * 按照模板的方式，导入承诺书（不支持用户自定义Excel）
	 * 
	 * @param type
	 *            承诺书类型
	 * @param excelFile
	 *            excel文件
	 * @param promiseBooks
	 *            承诺书
	 * @throws IOException
	 * @throws InvalidFormatException
	 */
	@Transactional(rollbackFor = Exception.class)
	@RequestMapping(value = "/importPromiseBookFiles.json")
	public RestServiceResult<Object> importPromiseBookFiles(@RequestParam("excelFile") MultipartFile excelFile,
			@RequestParam("promiseBooks") MultipartFile[] promiseBooks,
			@RequestParam(value = "ztType", required = true, defaultValue = "") String ztType,
			@RequestParam(value = "type", required = true, defaultValue = "") String type, HttpServletRequest request) {

		Long exS = excelFile.getSize();
		for (int i = 0; i < promiseBooks.length; i++) {
			exS += promiseBooks[i].getSize();
		}

		System.out.println(exS);

		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null != userInfo) {

			} else {
				ExceptionLogger.error("PromiseBookReportController#importPromiseBookFiles", "未获取到当前用户信息！");
				return new RestServiceResult<Object>(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
			}
		} else {
			ExceptionLogger.error("PromiseBookReportController#importPromiseBookFiles", "未获取到当前用户信息！");
			return new RestServiceResult<Object>(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
		}

		Long deptId = userInfo.getOfficeId();
		String deptName = userInfo.getOfficeName();
		Long areaId = userInfo.getAreaId();
		String areaName = userInfo.getAreaName();
		Long userId = userInfo.getId();
		String userName = userInfo.getRealName();
		Long parentId = userInfo.getParentId();
		Long topId = getTopId(deptId);
		if (topId == 0L) {
			topId = deptId;
		}

		RestServiceResult<Object> result = new RestServiceResult<Object>();
		if (null == excelFile || promiseBooks.length <= 0) {
			ExceptionLogger.error("PromiseBookReportController#importPromiseBookFiles", "文件不齐全！");
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("文件不齐全！！");

			return result;
		}

		if (excelFile.getOriginalFilename().contains(".")) {
			String fileType = excelFile.getOriginalFilename().substring(
					excelFile.getOriginalFilename().lastIndexOf("."), excelFile.getOriginalFilename().length());
			if (!".xls".equalsIgnoreCase(fileType) && !".xlsx".equalsIgnoreCase(fileType)
					&& !".XLS".equalsIgnoreCase(fileType) && !".XLSX".equalsIgnoreCase(fileType)) {

				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("Excel暂时不支持xls/xlsx以外的Excel的格式。");

				return result;

			}
		}

		for (int i = 0; i < promiseBooks.length; i++) {
			if (null == promiseBooks[i]) {
				continue;
			}
			if (promiseBooks[i].getOriginalFilename().contains(".")) {
				String fileType = promiseBooks[i].getOriginalFilename().substring(
						promiseBooks[i].getOriginalFilename().lastIndexOf("."),
						promiseBooks[i].getOriginalFilename().length());
				if (!".jpg".equalsIgnoreCase(fileType) && !".png".equalsIgnoreCase(fileType)
						&& !".JPG".equalsIgnoreCase(fileType) && !".PNG".equalsIgnoreCase(fileType)	&& !".PDF".equalsIgnoreCase(fileType) && !".pdf".equalsIgnoreCase(fileType)) {

					result.setCode(RestServiceResult.CODE_UNKNOW);
					result.setMsg("承诺书图片暂时不支持jpg/png/pdf以外的格式。");
					result.setData(promiseBooks[i].getOriginalFilename());
					return result;
				}
			}
		}

		int totalNum = 0;

		BufferedWriter bw = null;
		PromiseBookLog pbl = new PromiseBookLog();

		String batchId = UuidUtil.getInstance().getUUid();

		File excel = null;
		Map<String, String> promiseBookImgMap = new HashMap<>();
		try {
			//////////////////////////////////// 文件上传至服务器////////////////////////////////////////////////////////
			// 导入的文件夹路径
			String dirPath = absolutepath + File.separator + "upload" + File.separator + userInfo.getOfficeId()
					+ File.separator + "promise-book-import" + File.separator
					+ (new SimpleDateFormat("yyyy-MM-dd hh-mm-ss-SSS").format(new Date()));

			File dirFile = new File(dirPath);

			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}

			bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dirFile + File.separator + "log.log")));

			pbl.setLogPath(dirFile + File.separator + "log.log");

			excel = new File(dirFile + File.separator + excelFile.getOriginalFilename());

			// 导入excel文件
			excelFile.transferTo(excel);

			// 导入承诺书图片
			for (int i = 0; i < promiseBooks.length; i++) {

				if (null == promiseBooks[i]) {
					continue;
				}

				String oneName = promiseBooks[i].getOriginalFilename();
			
				String beforeName = oneName.substring(0, oneName.lastIndexOf("."));
			
				File promiseBookDir = new File(dirPath + File.separator + "promise-book");
				if (!promiseBookDir.exists()) {
					promiseBookDir.mkdir();
				}

				String newPath = promiseBookDir.getAbsolutePath() + File.separator
						+ promiseBooks[i].getOriginalFilename();

				promiseBookImgMap.put(beforeName, newPath);

				promiseBooks[i].transferTo(new File(newPath));
			}
		} catch (Exception e) {

			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("上传文件至服务器失败！");

			return result;
		}

		ArrayList<String> successLineNums = new ArrayList<String>();
		List<PromiseBookReport> pbrList = new ArrayList<>();
		try {
			//////////////////////////////////////////////// 解析excel//////////////////////////////////////////////////////////////
			// 针对不同类型的excel生成workbook工作簿
			Workbook wb = null;
			InputStream inp = new FileInputStream(excel);

			if (!inp.markSupported()) {
				inp = new PushbackInputStream(inp, 8);
			}
			if (POIFSFileSystem.hasPOIFSHeader(inp)) {
				wb = new HSSFWorkbook(inp);
			} else if (POIXMLDocument.hasOOXMLHeader(inp)) {
				wb = new XSSFWorkbook(OPCPackage.open(inp));
			} else {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("解析不了的Excel！");

				return result;
			}

			Sheet sheet = wb.getSheetAt(0);

			evaluator = wb.getCreationHelper().createFormulaEvaluator();

			// 获得总行数
			int rowNum = sheet.getLastRowNum() + 1;

			totalNum = rowNum - 1;

			lable: for (int f = 0; f < rowNum; f++) {

				boolean canInsert = true;

				Row row = sheet.getRow(f);
				PromiseBookReport pbr = new PromiseBookReport();

				if (isRowEmpty(row)) {
					totalNum = f - 1;
					break lable;
				}

				inLable: for (int j = 0; j < 4; j++) {
					Cell cell = row.getCell(j);
					// 根据不同类型"转化成字符串
					cell.setCellType(Cell.CELL_TYPE_STRING);

					String value = (cell.getStringCellValue());
				
//					if (null != cell && !(cell.toString().trim().equals(""))) {
//
//						int cellType = cell.getCellType();
//
//						if (cellType == Cell.CELL_TYPE_FORMULA) {
//							cellType = evaluator.evaluate(cell).getCellType();
//						}
//
//						switch (cellType) {
//
//						case Cell.CELL_TYPE_STRING:
//							value = (cell.getRichStringCellValue().getString()).trim();
//							value = StringUtils.isEmpty(value) ? "" : value;
//
//							break;
//						case Cell.CELL_TYPE_NUMERIC:
//							value = new DecimalFormat("#.######").format(cell.getNumericCellValue());
//							System.out.println("CELL_TYPE_NUMERIC = " + value);
//							break;
//						case HSSFCell.CELL_TYPE_BLANK:
//							value = "";
//							break;
//						default:
//							value = "";
//						}
//					}

					if (f == 0) {
						switch (j) {
						case 0:
							if ("100000".equals(ztType)) {
								if (!"企业名称".equals(value)) {
									result.setCode(RestServiceResult.CODE_UNKNOW);
									result.setMsg("当前模板选择不当！！");
									return result;
								}
							} else if ("100001".equals(ztType)) {
								if (!"自然人姓名".equals(value)) {
									result.setCode(RestServiceResult.CODE_UNKNOW);
									result.setMsg("当前模板选择不当！！");
									return result;
								}
							} else if ("100002".equals(ztType)) {
								if (!"机构名称".equals(value)) {
									result.setCode(RestServiceResult.CODE_UNKNOW);
									result.setMsg("当前模板选择不当！！");
									return result;
								}
							}
							break;
						case 1:
							if ("100000".equals(ztType) || "100002".equals(ztType)) {
								if (!"统一社会信用代码".equals(value)) {
									result.setCode(RestServiceResult.CODE_UNKNOW);
									result.setMsg("当前模板选择不当！！");
									return result;
								}
							} else if ("100001".equals(ztType)) {
								if (!"居民身份证件号".equals(value)) {
									result.setCode(RestServiceResult.CODE_UNKNOW);
									result.setMsg("当前模板选择不当！！");
									return result;
								}
							}
							break;
						case 2:
							if (!"信用承诺书名称".equals(value)) {
								result.setCode(RestServiceResult.CODE_UNKNOW);
								result.setMsg("当前模板选择不当！！");
								return result;
							}
							break;
						case 3:
							if (!"承诺日期".equals(value)) {
								result.setCode(RestServiceResult.CODE_UNKNOW);
								result.setMsg("当前模板选择不当！！");
								return result;
							}
							break;
						default:
							break;
						}
						continue inLable;
					}

					if (j == 0) {
						if (StringUtils.isEmpty(value)) {
							bw.write("第" + (f + 1) + "行，主体名称为空。");
							bw.newLine();
							bw.flush();
							canInsert = false;
						}
						if (value.length() > 100) {
							bw.write("第" + (f + 1) + "行，值过长（最大长度100）。");
							bw.newLine();
							bw.flush();
							canInsert = false;
						}
						pbr.setZtName(value);
					}

					if (j == 1) {
						if (!StringUtils.isEmpty(value)) {
							if (value.length() != 18) {
								bw.write("第" + (f + 1) + "行，主体代码不为18位。");
								bw.newLine();
								bw.flush();
								canInsert = false;
							}
						} else {
							if ("100001".equals(ztType)) {
								bw.write("第" + (f + 1) + "行，缺少身份证号码。");
								bw.newLine();
								bw.flush();
								canInsert = false;
							}
						}
						pbr.setTyshxydm(value);
					}

					if (j == 2) {
						if (StringUtils.isEmpty(value)) {
							bw.write("第" + (f + 1) + "行，缺少承诺书名称！。");
							bw.newLine();
							bw.flush();
							canInsert = false;
							pbr.setName("");
							pbr.setPath("");
							pbr.setHavBook("0");
						} else {
							String resu = getPathByName(value, promiseBookImgMap);
							if ("0".equals(resu)) {
								bw.write("第" + (f + 1) + "行，找不到对应名称的承诺书。");
								bw.newLine();
								bw.flush();
								pbr.setPath("");
								pbr.setName("");
								pbr.setName(value);
								pbr.setHavBook("0");
							} else {
								pbr.setPath(resu);
								pbr.setName(value);
								pbr.setHavBook("1");
							}
						}
					}
					if (j == 3) {
						if (StringUtils.isEmpty(value)) {
							bw.write("第" + (f + 1) + "行，承诺时间为空。");
							bw.newLine();
							bw.flush();
							canInsert = false;
						}
						
						pbr.setCnrq(value);
					}
				}

				// 封装插入对象
				pbr.setType(type);
				pbr.setDeptId(deptId);
				pbr.setReportDept(deptName);
				pbr.setZtType(ztType);
				pbr.setReportUserId(userId);
				pbr.setReportUserName(userName);
				pbr.setAreaId(areaId);
				pbr.setAreaName(areaName);
				pbr.setBatchId(batchId);
				pbr.setParentId(parentId);
				pbr.setTopId(topId);
				pbr.setBookStatus("2");
				pbr.setSbtype("平台");
				// 封装插入对象集合
				if (canInsert) {
					if (f != 0) {
						pbrList.add(pbr);
						successLineNums.add("第" + (f + 1) + "行");
					}
				}
			}

		} catch (Exception e) {
			try {
				bw.write("系统解析文件异常！");
				bw.newLine();
				bw.flush();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}

		Map<String, Object> map = new HashMap<>();

		int resultCount = 0;
		// 操作批量插入承诺书 和 日志
		try {
			if (pbrList.size() > 0) {
				resultCount = promiseBookReportService.savePromiseBooks(pbrList);
				pbl.setSuccessNum(resultCount);
			} else {
				pbl.setSuccessNum(0);
			}

			pbl.setTotalNum(totalNum);
			pbl.setBatchId(batchId);
			insertErrorLog(pbl);

			bw.newLine();
			bw.newLine();
			bw.newLine();
			bw.newLine();
			bw.write("一共处理数据" + totalNum + "条。");
			bw.newLine();
			bw.write("导入成功数量" + resultCount + "条。");
			bw.newLine();
			bw.write("导入成功行数：" + successLineNums.toString());
			bw.newLine();
			bw.flush();

			map.put("totalNum", totalNum);
			map.put("successNum", resultCount);
			map.put("batchId", batchId);

			result.setData(map);
			result.setCode(RestServiceResult.CODE_SUCCESS);
			result.setMsg("导入承诺书成功。");

			bw.close();
			return result;
		} catch (Exception e) {
			result.setMsg("导入时，服务器崩溃，请联系管理员！");
			result.setCode(RestServiceResult.CODE_UNKNOW);
		}

		return result;

	}

	/**
	 * 根据excel表格第三列的名字找他相对应的承诺书的路径
	 * 
	 * @param name
	 *            表格第三列的名字
	 * @param promiseBookPath
	 *            名字 == 路径的map
	 * @return
	 */
	private String getPathByName(String name, Map<String, String> promiseBookPath) {
		String result = promiseBookPath.get(name);

		if (StringUtils.isEmpty(result)) {
			return "0";
		}

		return result;
	}

	public static void main(String[] args) {
		List<Integer> list = new ArrayList<>();

		list.add(1);
		list.add(11);

		System.out.println(list.toString());
	}

	/**
	 * 判断excel某行是否是空行
	 * 
	 * @param row
	 * @return
	 */
	private static boolean isRowEmpty(Row row) {
		if (null == row) {
			return true;
		}

		for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
			Cell cell = row.getCell(c);
			if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 预览和下载承诺书图片
	 * 
	 * @param id
	 *            这一行的id
	 * @param previewOrDownload
	 *            预览或者下载参数 1：预览 2：下载
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/promiseBookPreview.json")
	public void promiseBookPreview(
			@RequestParam(value = "previewOrDownload", required = true, defaultValue = "") Integer param,
			@RequestParam(value = "id", required = true, defaultValue = "") Long id, HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null != userInfo) {

			} else {
				ExceptionLogger.error("PromiseBookReportController#promiseBookPreview", "未获取到当前用户信息！");
				throw new ServiceException("未获取到当前用户信息！");
			}
		} else {
			ExceptionLogger.error("PromiseBookReportController#promiseBookPreview", "未获取到当前用户信息！");
			throw new ServiceException("未获取到当前用户信息！");
		}

		String path = promiseBookReportService.promiseBookPreview(id);

		if (!new File(path).exists()) {
			throw new ServiceException("文件不存在，或者已经被移除！");
		}

		if (param == 1) {
			
			if(path.substring(path.length()-3,path.length()).equals("pdf")) {
        		response.setCharacterEncoding("UTF-8");
        		  	InputStream in = null;
        	        ServletOutputStream out = null;
        	        try {
        	            response.reset();
        	            out = response.getOutputStream();
        	            response.setContentType("application/pdf");
        	            in = new BufferedInputStream(new FileInputStream(path));
        	            int ch;
        	            while ((ch = in.read()) != -1) {
        	                out.print((char) ch);
        	            }
        	        } catch (Exception e) {
        	            e.printStackTrace();
        	        } finally {
        	            if (in != null) {
        	                in.close();
        	            }
        	            if (out != null) {
        	                out.flush();
        	                out.close();
        	            }
        	        }
                
                
        	}else {
        		try {
        		response.setContentType("image/png");       	      	
			response.setCharacterEncoding("UTF-8");
			
				OutputStream outputSream = response.getOutputStream();

				InputStream fileInputStream = new FileInputStream(path);
				byte[] data = this.toByteArray(fileInputStream);
				fileInputStream.close();

				InputStream in = new ByteArrayInputStream(data);
				in.close();
				int len = 0;

				byte[] buf = new byte[1024];
				while ((len = in.read(buf, 0, 1024)) != -1) {
					outputSream.write(buf, 0, len);
				}

				outputSream.close();
        	
			} catch (Exception e) {
				ExceptionLogger.error("PromiseBookReportController#promiseBookPreview",
    					"获取数据异常！ERROR：" + e.getMessage(), e);
				throw new ServiceException("解析承诺书异常，请联系管理员！");
			}
		} }else {
			FileUtils.downloadFile(path, response);
		}
	}

	private byte[] toByteArray(InputStream in) throws IOException {

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024 * 4];
		int n = 0;
		while ((n = in.read(buffer)) != -1) {
			out.write(buffer, 0, n);
		}
		return out.toByteArray();
	}

	// 表头展示列
	@RequestMapping(value = "/getOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
		return new RestServiceResult<>(PromiseBookReportEnum.getOptionalColumns());
	}

	// 高级查询自定义列表选项
	@RequestMapping(value = "/getAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {
		return new RestServiceResult<>(PromiseBookReportEnum.getAdvancedConditionColumns());
	}

	@RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {
		RestServiceResult<String> result = new RestServiceResult<String>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("SzjgController#addShowColunms", "未获取到当前用户信息！");
				return result;
			}

			String column = StringUtils.join(columns, ",");

			MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_ID, StringUtils.split(column, ","));
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		return result;
	}

	// private final static String FRONT_TABLE_ID = "content";
	// @RequestMapping(value = "/addShowColunms.json")
	// public RestServiceResult<String> addShowColunms(@RequestParam(value =
	// "columns", required = true) String[] columns,
	// @RequestParam(value = "type", defaultValue = "", required = true) String
	// type, HttpServletRequest request) {
	// RestServiceResult<SysUser> user =
	// remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
	// if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
	// SysUser userInfo = user.getData();
	// if (null != userInfo) {
	// MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_ID + "_" + type, columns);
	// } else {
	// ExceptionLogger.error("ContentController#addShowColunms", "未获取到当前用户信息！");
	// }
	// } else {
	// ExceptionLogger.error("ContentController#addShowColunms", "未获取到当前用户信息！");
	// }
	// return new RestServiceResult<>();
	// }

	/**
	 * 数据导出
	 * 
	 * @param type
	 * @param ztType
	 * @param bookStatus
	 * @param relationStatus
	 * @param condition
	 * @param columnEN
	 * @param page
	 * @param response
	 * @param request
	 * @throws IOException
	 */
	@RequestMapping(value = "/export.json")
	public void export(@RequestParam(value = "type", required = false, defaultValue = "") String type,
			@RequestParam(value = "ztType", required = false, defaultValue = "") String ztType,
			@RequestParam(value = "bookStatus", required = false, defaultValue = "") String bookStatus,
			@RequestParam(value = "relationStatus", required = false, defaultValue = "") String relationStatus,
			@RequestParam(value = "havBook", required = false, defaultValue = "") String havBook,
			@RequestParam(value = "sbtype", required = false, defaultValue = "") String sbtype,
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition,
			@RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN, Page page,
			HttpServletResponse response, HttpServletRequest request) throws IOException {

		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		String rolename ="";
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
		
			if (null == userInfo) {
				ExceptionLogger.error("PromiseBookReportController#savePromiseBook", "未获取到当前用户信息！");
				throw new ServiceException("未获取到当前用户信息！");
			}
		} else {
			ExceptionLogger.error("PromiseBookReportController#savePromiseBook", "未获取到当前用户信息！");
			throw new ServiceException("未获取到当前用户信息！");
		}

		// columnEN = columnEN.replace(",\"havBook\"" , "");

		Long areaId = userInfo.getAreaId();
		Long userId = userInfo.getId();
		Long parentId = userInfo.getParentId();
		Long deptId = userInfo.getOfficeId();
		int userType = userInfo.getUserType();

		String sql = "";
	

		page.setLimit(1000);
		List<String> columns = JSONArray.parseArray(columnEN, String.class);
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		if(rolename.equals("系统管理员")) {
			list = promiseBookReportService.getPromiseBooksByConditionForPage(type, ztType,
					bookStatus, havBook, sql, columns, null, condition, page,null,null,sbtype);
		}
		else if(rolename.equals("部门管理员")) {
			list = promiseBookReportService.getPromiseBooksByConditionForPage(type, ztType,
					bookStatus, havBook, sql, columns, null, condition, page,deptId,null,sbtype);
		}else {
			list = promiseBookReportService.getPromiseBooksByConditionForPage(type, ztType,
					bookStatus, havBook, sql, columns, null, condition, page,deptId,userId,sbtype);
		}
		List<OptionalColumn> optionalColumns = PromiseBookReportEnum.getOptionalColumns();
		ExcelUtil.downloadExcel(response, list, userInfo.getOfficeName() + "上传承诺书记录",
				userInfo.getOfficeName() + "上传承诺书记录", columns, optionalColumns);
	}

	/**
	 * 模板下载
	 * 
	 * @param response
	 * @param request
	 * @throws IOException
	 */
	@RequestMapping(value = "/templeteDownload.json")
	public void templeteDownload(HttpServletResponse response, HttpServletRequest request) throws IOException {

		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo) {
				ExceptionLogger.error("PromiseBookReportController#savePromiseBook", "未获取到当前用户信息！");
				throw new ServiceException("未获取到当前用户信息！");
			}
		} else {
			ExceptionLogger.error("PromiseBookReportController#savePromiseBook", "未获取到当前用户信息！");
			throw new ServiceException("未获取到当前用户信息！");
		}

		FileUtils.downloadFile(PromiseBookReportController.class.getClassLoader().getResource("mb/承诺书模板.rar").getPath(),
				response);
	}

	/**
	 * 自我审核 支持批量
	 * 
	 * @param id
	 * @param request
	 * @throws IOException
	 */
	@RequestMapping(value = "/approvalMyself.json")
	public RestServiceResult<Object> approvalMyself(
			@RequestParam(value = "ids", required = false, defaultValue = "") String ids, HttpServletRequest request)
			throws IOException {

		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo) {
				ExceptionLogger.error("PromiseBookReportController#approvalMyself", "未获取到当前用户信息！");
				throw new ServiceException("未获取到当前用户信息！");
			}
		} else {
			ExceptionLogger.error("PromiseBookReportController#approvalMyself", "未获取到当前用户信息！");
			throw new ServiceException("未获取到当前用户信息！");
		}

		boolean b = false;

		RestServiceResult<Object> result = new RestServiceResult<Object>();

		List<Long> idList = new ArrayList<>();
		String[] idArr = ids.split(",");
		for (String id : idArr) {
			idList.add(Long.parseLong(id));
		}

		Iterator<Long> it = idList.iterator();
		try {
			while (it.hasNext()) {

				Long id = it.next();

				Map<String, String> isOkMap = promiseBookReportService.selectCount(id);

				String havBook = isOkMap.get("havBook");
				String bookStatus = isOkMap.get("bookStatus");

				if ("0".equals(havBook)) {
					it.remove();
				}

				if ("1".equals(bookStatus) || "2".equals(bookStatus)) {
					b = true;
					it.remove();
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		if (idList.size() == 0) {
			if (b) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("缺少承诺书图片,待审核和审批通过的数据无法提交审核！");
			} else {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("无法提交审核，缺少承诺书图片！");
				return result;
			}
			return result;
		}

		try {
			int successCount = promiseBookReportService.approvalMyself(idList);

			result.setCode(RestServiceResult.CODE_SUCCESS);
			result.setMsg("成功修改" + successCount + "条");

			return result;

		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("审核失败！");

			return result;
		}

	}

	/**
	 * 查询一行信息
	 * 
	 * @param id
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/selectOne.json")
	public RestServiceResult<Map<String, Object>> selectOne(
			@RequestParam(value = "id", required = true, defaultValue = "") Long id, HttpServletRequest request)
			throws IOException {

		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo) {
				ExceptionLogger.error("PromiseBookReportController#approvalMyself", "未获取到当前用户信息！");
				throw new ServiceException("未获取到当前用户信息！");
			}
		} else {
			ExceptionLogger.error("PromiseBookReportController#approvalMyself", "未获取到当前用户信息！");
			throw new ServiceException("未获取到当前用户信息！");
		}

		RestServiceResult<Map<String, Object>> result = new RestServiceResult<Map<String, Object>>();

		try {
			Map<String, Object> map = promiseBookReportService.selectOne(id);

			result.setData(map);
			result.setCode(RestServiceResult.CODE_SUCCESS);

		} catch (Exception e) {
			ExceptionLogger.error("PromiseBookReportController#selectOne", "系统异常，请联系管理员！");
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("系统异常，请联系管理员！");
		}

		return result;
	}

	private void insertErrorLog(PromiseBookLog promiseBookLog) {
		promiseBookReportService.insertErrorLog(promiseBookLog);
	}

	/**
	 * 查詢日志列表
	 * 
	 * @param page
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/selectAllLogs.json")
	public RestServiceResult<List<Map<String, Object>>> selectAllLogs(Page page, HttpServletRequest request) {

		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo) {
				ExceptionLogger.error("PromiseBookReportController#selectAllLogs", "未获取到当前用户信息！");
				throw new ServiceException("未获取到当前用户信息！");
			}
		} else {
			ExceptionLogger.error("PromiseBookReportController#selectAllLogs", "未获取到当前用户信息！");
			throw new ServiceException("未获取到当前用户信息！");
		}

		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();

		try {
			List<Map<String, Object>> map = promiseBookReportService.selectAllLogs(page);

			result.setData(map);
			result.setCode(RestServiceResult.CODE_SUCCESS);
			result.setCount(page.getTotalCount());

		} catch (Exception e) {
			ExceptionLogger.error("PromiseBookReportController#selectAllLogs", "系统异常，请联系管理员！");

			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("系统异常，请联系管理员！");
		}

		return result;
	}

	/**
	 * 日志下载
	 * 
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/downloadLog.json")
	public void downloadLog(@RequestParam(value = "id", required = true, defaultValue = "") String id,
			HttpServletRequest request, HttpServletResponse response) {

		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null != userInfo) {

			} else {
				ExceptionLogger.error("PromiseBookReportController#promiseBookPreview", "未获取到当前用户信息！");
				throw new ServiceException("未获取到当前用户信息！");
			}
		} else {
			ExceptionLogger.error("PromiseBookReportController#promiseBookPreview", "未获取到当前用户信息！");
			throw new ServiceException("未获取到当前用户信息！");
		}

		String path = promiseBookReportService.getDownloadLogPath(id);

		if (!new File(path).exists()) {
			throw new ServiceException("文件不存在，或者已经被移除！");
		}

		FileUtils.downloadFile(path, response);

	}

	private Long getTopId(Long deptId) {
		String allParentIds = promiseBookReportService.selectAllParentIds(deptId);

		if (StringUtils.isEmpty(allParentIds)) {
			return 0L;
		}

		List<Long> listIds = Arrays.asList(allParentIds.split(",")).stream().map(s -> Long.parseLong(s.trim()))
				.collect(Collectors.toList());

		return listIds.get(0);
	}

	@IgnoreAuthority
	@RequestMapping("/webAddXycn.json")
	public RestServiceResult<Object> webAddXycn(String condition, HttpServletRequest request) {

		RestServiceResult<Object> result = new RestServiceResult<>();
		try {
			Map<String, String> parseObject = JSONObject.parseObject(condition, Map.class);
			String type = parseObject.get("type");
			String dept = parseObject.get("dept");
			String cnrq = parseObject.get("cnrq");
			String deptName = parseObject.get("deptname");
			String ztmc = parseObject.get("ztmc");
			String cns = parseObject.get("cns");
			String ztType = parseObject.get("zt_type");
			String cnsfilename = parseObject.get("cnsfilename");

			byte[] decode = Base64.decode(cns, CharsetUtil.CHARSET_UTF_8);

			// 导入的文件夹路径
			String dirPath = absolutepath + File.separator + "upload" + File.separator + dept + File.separator
					+ "promise-book-import" + File.separator
					+ (new SimpleDateFormat("yyyy-MM-dd hh-mm-ss-SSS").format(new Date()));

			File dirFile = new File(dirPath);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
			 getFileByBytes(decode,dirPath,cnsfilename);

			

			String batchId = UuidUtil.getInstance().getUUid();
			List<PromiseBookReport> pbrList = new ArrayList<>();
			PromiseBookReport pbr = new PromiseBookReport();
			pbr.setZtName(ztmc);
			pbr.setDeptId(Long.valueOf(dept));
			pbr.setName(cnsfilename);
			pbr.setPath(dirPath + File.separator  + cnsfilename);
			pbr.setType(type);
			pbr.setReportDept(deptName);
			pbr.setZtType(ztType);
			pbr.setBatchId(batchId);
			pbr.setHavBook("1");
			pbr.setBookStatus("1");
			pbr.setCnrq(cnrq);
			pbr.setSbtype("门户网站");
			pbrList.add(pbr);

			int a = promiseBookReportService.savePromiseBooks(pbrList);
			if (a > 0) {
				result.setData("添加成功");
			} else {
				result.setData("添加失败");
			}
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("xycn#webAddXycn", "信用承诺添加异常！ERROR:" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("信用承诺添加异常！");
			return result;
		}
	}

	// 将Byte数组转换成文件
	public static void getFileByBytes(byte[] bytes, String filePath, String fileName) {
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		File file = null;
		try {
			File dir = new File(filePath);
			if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
				dir.mkdirs();
			}
			file = new File(filePath + file.separator + fileName);
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(bytes);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
